<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="wholeData.tableData"
        highlight-current-row
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="任务编号"
          prop="id"
          width="100"
          align="center"
        />
        <el-table-column label="字符串" prop="taskKey" width="150" />
        <el-table-column label="cron执行表达式" prop="taskCron" width="150" />
        <el-table-column label="描述" prop="taskDesc" min-width="150" />
        <el-table-column label="状态" align="center" width="130">
          <template #default="scope">
            <el-tag v-if="scope.row.startFlag" type="success">启动</el-tag>
            <el-tag v-else type="info">停止</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="restart(scope.row)"
							v-hasPerm="['resource:scheduled:do']"
            >
              <i-ep-position />重启
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
							v-hasPerm="['resource:scheduled:update']"
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="stop(scope.row)"
							v-hasPerm="['resource:scheduled:do']"
            >
              <i-ep-delete />停止
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="start(scope.row)"
							v-hasPerm="['resource:scheduled:do']"
            >
              <i-ep-delete />启动
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 定时任务弹窗 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="600px"
      @close="closeDialog"
    >
      <el-form
        ref="roleFormRef"
        :model="wholeData.formData"
        label-width="100px"
      >
        <el-form-item label="编号">
          <el-input disabled v-model="wholeData.formData.id" />
        </el-form-item>

        <el-form-item label="描述">
          <el-input v-model="wholeData.formData.taskDesc" />
        </el-form-item>

        <el-form-item label="字符串">
          <el-input disabled v-model="wholeData.formData.taskKey" />
        </el-form-item>

        <el-form-item label="cron表达式">
          <div style="display: flex">
            <el-input disabled v-model="wholeData.formData.taskCron" />
            <el-button
              type="primary"
              style="margin-left: 5px"
              plain
              @click="openScheduledTasksDialog"
              >生成表达式</el-button
            >
          </div>
        </el-form-item>

        <el-form-item label="初始状态">
          <el-switch
            v-model="wholeData.formData.initStartFlag"
            class="ml-2"
            style="

              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 生成表达式弹窗  -->
    <el-dialog
      v-model="ScheduledTasksDialog.visible"
      @close="closeScheduledTasksDialogDialog"
      width="900px"
    >
      <crontab
        @hide="closeScheduledTasksDialogDialog"
        @fill="changeCron"
        :expression="wholeData.formData.taskCron"
      >
      </crontab>

    </el-dialog>
  </div>
</template>

<script lang="ts">
export default {
  name: 'role',
	components: {
		Crontab
  },
};
</script>

<script setup lang="ts">

import {getScheduledTasks,Restart,Start,Stop,Update} from '@/api/timer';


import Crontab from "@/components/Crontab/index.vue";

const loading = ref(false);

// const queryParams = reactive<RoleQuery>({
//   pageNum: 1,
//   pageSize: 10
// });

const dialog = reactive<DialogOption>({
  visible: false,
});

const ScheduledTasksDialog = reactive<DialogOption>({
  visible: false,
});

const wholeData = reactive({
  //数据大本营
  tableData: [],
  formData: {},
  //  cronCache :'',
});

/**
 * 查询
 */
function Search() {
  loading.value = true;
  getScheduledTasks()
    .then((res) => {
      console.log(res);
      wholeData.tableData = res.data.task;
    })
    .finally(() => {
      loading.value = false;
    });
}

function restart(row: any) {
  loading.value = true;
  Restart(row.taskKey)
    .then((res) => {
      console.log(res);
      Search();
    })
    .finally(() => {
      loading.value = false;
    });
}

function start(row: any) {
  loading.value = true;
  Start(row.taskKey)
    .then((res) => {
      console.log(res);
      Search();
    })
    .finally(() => {
      loading.value = false;
    });
}

function stop(row: any) {
  loading.value = true;
  Stop(row.taskKey)
    .then((res) => {
      console.log(res);
      Search();
    })
    .finally(() => {
      loading.value = false;
    });
}

// /**
//  * 行checkbox change事件
//  */
// function handleSelectionChange(selection: any) {
//   ids.value = selection.map((item: any) => item.id);
// }

/**
 * 打开弹窗
 *
 * @param roleId
 */
function openDialog(row: any) {
  dialog.visible = true;
  dialog.title = "修改定时任务";
  wholeData.formData = row;
}

function openScheduledTasksDialog() {
  // alert('子窗打开');
  // closeDialog();
  ScheduledTasksDialog.visible = true;
  // wholeData.cronCache = wholeData.formData.taskCron;
  // wholeData.formData.taskCron = '';
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  // resetForm();
}

function closeScheduledTasksDialogDialog() {
  ScheduledTasksDialog.visible = false;
  // if(wholeData.formData.taskCron === '')
  //   	wholeData.formData.taskCron = wholeData.cronCache;
  // resetForm();
  // if( typeof a === "object" || a === null)
  //  	wholeData.formData.taskCron = wholeData.cronCache;
}

function confirm() {
  const taskForm = {
    id: wholeData.formData.id,
    taskDesc: wholeData.formData.taskDesc,
    taskCron: wholeData.formData.taskCron,
    initStartFlag: wholeData.formData.initStartFlag,
    taskKey: wholeData.formData.taskKey,
  };
  loading.value = true;
  console.log(taskForm);
  Update(taskForm)
    .then((res) => {
      console.log(res);
      successMessage(res.message);
      Search();
    })
    .finally(() => {
      loading.value = false;
    });
  closeDialog();
}

function changeCron(cronText: string) {
  wholeData.formData.taskCron = cronText;
}

const successMessage = (message: string) => {
  ElMessage({
    message: message,
    type: "success",
  });
};

//  function confirmCron(){
// 	 if(wholeData.cronCache != '')
// 			 wholeData.formData.taskCron = wholeData.cronCache;
//  }

/**
 * 删除
 */
// function handleDelete(roleId?: number) {
//   const roleIds = [roleId || ids.value].join(',');
//   if (!roleIds) {
//     ElMessage.warning('请勾选删除项');
//     return;
//   }

//   ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   }).then(() => {
//     loading.value = true;
//     deleteRoles(roleIds)
//       .then(() => {
//         ElMessage.success('删除成功');
//         resetQuery();
//       })
//       .finally(() => (loading.value = false));
//   });
// }

onMounted(() => {
  Search();
});
</script>
